import { useEffect, useState, useRef } from 'react'

import { Input, Button, Typography, Table, message } from 'antd';
import { SearchOutlined, DownloadOutlined, CloudUploadOutlined, ReloadOutlined, PlusCircleOutlined } from '@ant-design/icons';

import styles from './index.module.css'

//网络
import { queryBranch, getAuthCode, dowanloadBranchTemplateUrl, uploadBranchTemplate } from '../../utils/axiosRequest/api'


//列
import { columns } from '../../constant/branchColumn.js'

//查询网点
function Branch() {
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //表格展示数据
    const [showDataSource, setDataSource] = useState([]);
    //表格加载状态
    const [tabeLoadStatus, setTabeLoadStatus] = useState(false);
    //默认一页面显示几条数据
    const [pageSize, setPageSize] = useState(8);
    const containerRef = useRef(null);

    //[]空数组相当于componentDidMount
    useEffect(() => {
        //动态计算每页展示多少条数据
        if (!containerRef.current) return;
        const observer = new ResizeObserver((entries) => {
            for (let entry of entries) {
                const { height } = entry.contentRect;
                // 计算适合的行数
                const rowHeight = 85; // 预估行高
                const headerHeight = 90; // 表头高度
                const newPageSize = Math.floor((height - headerHeight) / rowHeight);
                setPageSize(Math.max(1, newPageSize));//避免负数
            }
        });
        observer.observe(containerRef.current);
        initData()
        return () => {
            observer.disconnect();
        }
    }, []);

    
    function initData() {
        setTabeLoadStatus(true)
        const params = new Map()
        queryBranch(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //处理数据
                    hadleData(data)
                    messageApi.open({ type: 'success', content: '数据已更新' });
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setTabeLoadStatus(false)
            })
            .catch(error => {
                setTabeLoadStatus(false)
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //处理数据
    function hadleData(data) {
        const branchList = data.data;
        const tempData = [];
        for (let i = 0; i < branchList.length; i++) {
            tempData.push({
                key: i,
                serial: i,
                updateTime: branchList[i].lastUpdateTime,
                branchName: branchList[i].branchName,
                bankName: branchList[i].bankName,
                branchAddress: branchList[i].branchAddress,
                belongDistricts: branchList[i].belongDistricts,
                operation: branchList[i],
            })
        }
        //排序->根据更新时间排序
        tempData.sort((a, b) => b.updateTime.localeCompare(a.updateTime))
        //然后添加serial序号
        const dataWithSerial = tempData.map((item, index) => ({
            ...item,
            serial: index + 1  // 从1开始编号
        }));
        setDataSource(dataWithSerial)
    }

    //点击获取模板
    function getTemplate() {
        const params = new Map()
        getAuthCode(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //处理数据
                    const authCode = data.data.authCode;
                    downLoadFile(authCode)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setTabeLoadStatus(false)
            })
            .catch(error => {
                setTabeLoadStatus(false)
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //开始下载文件
    function downLoadFile(authCode) {
        window.open(dowanloadBranchTemplateUrl(authCode), '_blank');
    }

    //点击上传模板文件
    function clickUploadTemplate() {
        document.getElementById('fileInput').click();
    }
    //文件选择
    function fileSelected() {
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (file === undefined) {
            //用户取消选择
            messageApi.open({ type: 'error', content: '取消选择' });
            return
        }
        //判断xlsx文件
        if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            messageApi.open({ type: 'error', content: '请选择xlsx文件' });
            return
        }
        //文件大小判断
        const fileSize = file.size//文件大小（字节）
        if (fileSize > 1024 * 1024 * 1) {
            messageApi.open({ type: 'error', content: '请选择小于1M的文件' });
            return
        }
        //先获取认证code
        const params = new Map()
        getAuthCode(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //处理数据
                    const authCode = data.data.authCode;
                    uploadFile(authCode, file)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setTabeLoadStatus(false)
            })
            .catch(error => {
                setTabeLoadStatus(false)
                messageApi.open({ type: 'error', content: error.message });
            });
        // 重置文件输入，允许再次选择相同文件
        fileInput.value = '';
    }

    //上传文件
    function uploadFile(authCode, file) {
        const formData = new FormData();
        formData.append('file', file); // 'file'是你服务器端接收文件的字段名
        const params = new Map()
        params.set('authCode', authCode)
        params.set('formData', formData)
        uploadBranchTemplate(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    messageApi.open({ type: 'success', content: '上传成功' });
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //刷新
    function refreshData() {
        initData()
    }

    //搜索框
    function onChange(val) {
        //搜索框的内容
        let value = val.target.value
    }

    //点击分页
    function handleTableChange(pagination, filters, sorter) {
        const current = pagination.current;//当前第几页
        const pageSize = pagination.pageSize;//每页展示多少条
    };

    return (
        <div className={styles.container}>
            <input type="file" id="fileInput" style={{ display: 'none' }} onChange={fileSelected} />
            {contextHolder}
            <div className={styles.search_box}>
                <Input onChange={onChange} size="default" placeholder="请输入网点名称..." prefix={<SearchOutlined />} allowClear />
                <Button type="primary" className={styles.search_btn}>搜索网点</Button>
            </div>
            <div className={styles.template_box}>
                <Button type="primary" onClick={refreshData} icon={<ReloadOutlined />} size={'small'}>刷新</Button>
                <Button onClick={getTemplate} icon={<DownloadOutlined />} className={styles.template_download_text} size={'small'}>下载模板</Button>
                <Button onClick={clickUploadTemplate} icon={<CloudUploadOutlined />} size={'small'} className={styles.template_download_text}>批量导入</Button>
                <Button type="primary" icon={<PlusCircleOutlined />} className={styles.template_download_text} size={'small'}>新增网点</Button>
            </div>
            <div ref={containerRef} className={styles.data_box}>
                <Table loading={tabeLoadStatus} onChange={handleTableChange} bordered={true} pagination={{ defaultCurrent: '1', total: showDataSource.length, showSizeChanger: false, pageSize: pageSize }} dataSource={showDataSource} columns={columns} />
            </div>

        </div>
    )
}

export default Branch;